import { observer } from 'mobx-react'
import React, { useRef } from 'react'
import { Tooltip, Button, Avatar } from 'antd'
import { useMobxStore } from '@/mobx/store';
import { UserOutlined } from '@ant-design/icons';
import { baseURL } from '@/api/request';
import { Ajax } from './../../api/api';

const MyAvatar = () => {
    const {
        MyData: {
            userInfo,
            changeUserInfo
        }
    } = useMobxStore()

    const fileRef: any = useRef()

    const startUpload = () => {
        fileRef.current.click()
    }

    const todoUpload = async () => {
        let file = fileRef.current.files[0]
        let data = new FormData()
        data.append('file', file)
        let res: any = await Ajax.uploadfile(data)
        if (res.code == 200) {
            let res2: any = await Ajax.changeuserinfo({
                avatar: res.path
            })
            if (res2.code == 200) {
                changeUserInfo(userInfo.set('avatar', res.path))
            }
        }
    }

    return (
        <Tooltip title={'更换头像'}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
                <input type='file' ref={fileRef} onChange={todoUpload} style={{ display: 'none' }} />
                {
                    userInfo.get('avatar') ?
                        <Avatar size={32} onClick={startUpload} src={userInfo.get('avatar')?.replace(/public/, baseURL)} />
                        :
                        <Avatar size={32} onClick={startUpload} icon={<UserOutlined />} style={{ background: '#b5b5b5' }} />
                }
            </div>
        </Tooltip>
    )
}

export default observer(MyAvatar)